<template>
  <el-dialog title="编辑列表结构" :visible.sync="visible" width="1500px" :close-on-click-modal="false" :before-close="handleClose">
    <div class="oplist">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="addGroup">添加组</el-button>
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="addCol(null)">添加列</el-button>
    </div>
    <w-table :data="dataSource" :columns="columns" row-key="Id" :is-paging="false">
      <template slot="isNotNull" slot-scope="e">
        {{ e.row.IsNotNull ? '是' : '否' }}
      </template>
      <template slot="width" slot-scope="e">
        <span v-if="e.row.Width">{{ e.row.Width + 'px' }}</span>
      </template>
      <template slot="defaultVal" slot-scope="e">
        <span v-if="e.row.DefaultVal && e.row.DefaultVal.startsWith('[') && e.row.DefaultVal.endsWith(']')">{{ defNames[e.row.DefaultVal] == null ? e.row.DefaultVal: defNames[e.row.DefaultVal] }}</span>
        <span v-else-if="e.row.DefaultVal">{{ e.row.DefaultVal }}</span>
      </template>
      <template slot="action" slot-scope="e">
        <template v-if="e.row.IsGroup">
          <el-button type="success" size="mini" circle icon="el-icon-plus" @click="addCol(e.row.Id)" />
          <el-button type="primary" size="mini" circle icon="el-icon-edit" @click="editGroup(e.row.Id)" />
          <el-button v-if="e.row.Children== null || e.row.Children.length === 0" type="danger" size="mini" circle icon="el-icon-delete" @click="dropGroup(e.row)" />
        </template>
        <template v-else>
          <el-button type="primary" size="mini" circle icon="el-icon-edit" @click="editCol(e.row.Id)" />
          <el-button type="danger" size="mini" circle icon="el-icon-delete" @click="dropCol(e.row)" />
        </template>
      </template>
      <template slot="sort" slot-scope="e">
        <el-button v-if="e.row.Sort > prtSort[e.row.groupId].min" :type="e.row.groupId == 'root' ? 'primary': 'default'" icon="el-icon-caret-top" circle @click="setSort(e.row, false)" />
        <el-button v-if="e.row.Sort < prtSort[e.row.groupId].max" :type="e.row.groupId == 'root' ? 'primary': 'default'" icon="el-icon-caret-bottom" circle @click="setSort(e.row, true)" />
      </template>
    </w-table>
    <formGroupEdit :id="groupId" :form-id="formId" :table-id="table.Id" :columns="dataSource" :visible.sync="groupVisible" @close="closeGroup" />
    <edit-column :id="id" :form-body="formBody" :form-id="formId" :group-id="groupId" :table="table" :columns="dataSource" :visible.sync="colVisible" @close="closeCol" />
  </el-dialog>
</template>

<script>
import {
  GetQueryTable
} from '@/customForm/api/table'
import formGroupEdit from './formGroupEdit.vue'
import editColumn from '../components/editColumn.vue'
import * as groupApi from '@/customForm/api/formGroup'
import * as columnApi from '@/customForm/api/column'
import { DictItemDic } from '@/customForm/config/formConfig'
import { GetItemName } from '@/api/base/dictItem'
export default {
  components: {
    formGroupEdit,
    editColumn
  },
  props: {
    formId: {
      type: String,
      default: null
    },
    formBody: {
      type: Array,
      default: null
    },
    table: {
      type: Object,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: null,
      groupId: null,
      groupVisible: false,
      colVisible: false,
      isRefresh: false,
      defNames: {},
      prtSort: {},
      columns: [{
        key: 'Title',
        title: '标题',
        align: 'left',
        minWidth: 150
      }, {
        key: 'Name',
        title: '列名',
        align: 'center',
        minWidth: 150
      }, {
        key: 'Description',
        title: '说明',
        align: 'right',
        minWidth: 255
      }, {
        key: 'ControlName',
        title: '控件名',
        align: 'center',
        width: 150
      }, {
        key: 'IsNotNull',
        title: '不能为空',
        align: 'center',
        width: 80,
        slotName: 'isNotNull'
      }, {
        key: 'DefaultVal',
        title: '默认值',
        align: 'center',
        width: 100,
        slotName: 'defaultVal'
      }, {
        key: 'Width',
        title: '宽度',
        align: 'right',
        width: 100,
        slotName: 'width'
      }, {
        key: 'Sort',
        title: '排序位',
        align: 'center',
        width: 150,
        slotName: 'sort'
      }, {
        key: 'Action',
        title: '操作',
        align: 'left',
        width: 150,
        fixed: 'right',
        slotName: 'action'
      }],
      dataSource: []
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.isRefresh = false
          this.load()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.initDefName()
  },
  methods: {
    async initDefName() {
      this.defNames = await GetItemName(DictItemDic.controlDefVal)
    },
    async setSort(row, isNext) {
      const res = await columnApi.SetQuerySort({
        TableId: this.table.Id,
        GroupId: row.groupId === 'root' ? 0 : row.groupId,
        Id: row.Id,
        IsNext: isNext
      })
      if (res) {
        this.isRefresh = true
        this.load()
      }
    },
    dropGroup(row) {
      const title = '确认删除组 ' + row.Title + '?'
      const that = this
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.submitDrop(row.Id)
      })
    },
    async submitDrop(id) {
      await groupApi.Delete(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.dataSource = this.dataSource.filter(a => a.Id !== id)
      this.isRefresh = true
    },
    dropCol(row) {
      const title = '确认删除列 ' + row.Title + '?'
      const that = this
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.submitDropCol(row.Id)
      })
    },
    async submitDropCol(id) {
      await columnApi.Delete(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.isRefresh = true
      this.load()
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close', this.isRefresh)
    },
    closeCol(isRefresh) {
      if (isRefresh) {
        this.isRefresh = true
        this.load()
      }
    },
    closeGroup(isRefresh) {
      if (isRefresh) {
        this.isRefresh = true
        this.load()
      }
    },
    editGroup(id) {
      this.groupId = id
      this.groupVisible = true
    },
    addCol(gid) {
      this.groupId = gid
      this.id = null
      this.colVisible = true
    },
    editCol(id) {
      this.groupId = null
      this.id = id
      this.colVisible = true
    },
    addGroup() {
      this.groupId = null
      this.groupVisible = true
    },
    format(col, gId) {
      if (col.IsGroup) {
        let minSort = Number.MAX_VALUE
        let maxSort = 1
        col.groupId = gId
        col.Children.forEach(c => {
          if (c.Sort > maxSort) {
            maxSort = c.Sort
          }
          if (c.Sort < minSort) {
            minSort = c.Sort
          }
          this.format(c, col.Id)
        })
        this.prtSort[col.Id] = {
          min: minSort,
          max: maxSort
        }
      } else {
        col.groupId = gId
      }
    },
    async load() {
      this.groupId = null
      this.id = null
      const list = await GetQueryTable(this.table.Id)
      let minSort = Number.MAX_VALUE
      let maxSort = 1
      list.forEach(c => {
        c.colSpan = {
          Title: c.IsGroup ? 7 : 1
        }
        this.format(c, 'root')
        if (c.Sort > maxSort) {
          maxSort = c.Sort
        }
        if (c.Sort < minSort) {
          minSort = c.Sort
        }
      })
      this.prtSort['root'] = {
        min: minSort,
        max: maxSort
      }
      this.dataSource = list
    }
  }
}
</script>

<style scoped>
.oplist {
    width: 100%;
    padding: 10px;
    text-align: right;
  }
</style>
